package com.dagene.weixin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Component;

import com.dagene.weixin.entity.Admin;


@Component
public class SessionFilter implements Filter {
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//WeixinUrlIdMap.start();
	}
	
	private HttpClient getHttpClient(){     
		HttpClient httpClient= HttpClientBuilder.create().build();
        return httpClient;  
    } 

	private JSONObject getJSONObjectByGet(String requestUrl){
		BufferedReader bufferedReader=null;  
		HttpResponse httpResponse = null;
		JSONObject resultJsonObject=null;
        try {  
            //HttpClient发出一个HttpGet请求  
        	HttpClient httpClient = getHttpClient();
            httpResponse=httpClient.execute(new HttpGet(requestUrl));         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        //得到httpResponse的状态响应码  
        if (httpResponse==null) System.out.println("httpResponse==null");
        if (httpResponse.getStatusLine()==null) System.out.println("httpResponse.getStatusLine()==null");
        int statusCode=httpResponse.getStatusLine().getStatusCode();  
        if (statusCode==HttpStatus.SC_OK) {  
            //得到httpResponse的实体数据  
            HttpEntity httpEntity=httpResponse.getEntity();  
            StringBuilder entityStringBuilder=new StringBuilder();
            if (httpEntity!=null) {  
                try {  
                    bufferedReader=new BufferedReader  
                    (new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);  
                    String line=null;  
                    while ((line=bufferedReader.readLine())!=null) {  
                        entityStringBuilder.append(line);  
                    }  
                    //利用从HttpEntity中得到的String生成JsonObject  
                    resultJsonObject =  JSONObject.fromObject(entityStringBuilder.toString());
                   // resultJsonObject=  new JSONParser().parse(entityStringBuilder.toString()); 
                    
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return resultJsonObject; 
		
	}
	
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String oaname = null;

		if (httpServletRequest.getParameter("code")!=null) {
			System.out.println(httpServletRequest.getParameter("code"));
			String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"
					+ "appid=" + Constants.APPID + "&secret=" + Constants.APPSECRET
					+ "&code=" + httpServletRequest.getParameter("code") + "&grant_type=authorization_code";
			System.out.println("accessTokenUrl:" + new Date());
			System.out.println(accessTokenUrl);
			JSONObject jsonObj = getJSONObjectByGet(accessTokenUrl);
			String accessToken = null;
			String refreshToken = null;
			String openid = null;
			
			Admin tmpadmin = new Admin();
			tmpadmin.setId(1);
			tmpadmin.setUsername("admin");
			httpServletRequest.getSession().setAttribute("admin", tmpadmin);
			
			if (jsonObj.has("access_token")) {
				accessToken = jsonObj.get("access_token").toString();
			}
			if (jsonObj.has("refresh_token")) {
				refreshToken = jsonObj.get("refresh_token").toString();
			}
			if (jsonObj.has("openid")) {
				openid = jsonObj.get("openid").toString();
				System.out.println("openid:" + openid);
				try {
					httpServletRequest.getSession().setAttribute("weixin", openid);
					
			    	//
					chain.doFilter(request, response);
					return;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		} else {
			if (httpServletRequest.getSession().getAttribute("weixin")==null) {
				//httpServletRequest.getSession().setAttribute("weixin", "oys2GxKWgpvePu3fT69KhMBaDSqU");
			}
		}
		
//		if (httpServletRequest.getSession().getAttribute("weixin") == null) {
//			//if (!SecurityUtils.getSubject().isAuthenticated()) {
//			//判断session里是否有用户信息			
//			if (httpServletRequest.getHeader("x-requested-with") != null
//					&& httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//				//如果是ajax请求响应头会有，x-requested-with
//				httpServletResponse.setHeader("sessionstatus", "timeout");//在响应头设置session状态
//				return;
//			}
//		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
